package com.example.com.myapplication.activity;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

/**
 * @author by licheng on 2017/8/4.
 */

public abstract class PermissionActivity extends Activity {

    private static final int REQUEST_PERMISSION = 0X0001;

    protected boolean isPermissionGranted;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkPermissionList(getPermissionList());
    }

    private void checkPermissionList(String[] permissionList) {
        for (String permission : permissionList) {
            int status = ContextCompat.checkSelfPermission(this, permission);
            isPermissionGranted = (PackageManager.PERMISSION_GRANTED == status);
            if (!isPermissionGranted && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this, new String[]{permission}, REQUEST_PERMISSION);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (REQUEST_PERMISSION == requestCode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                isPermissionGranted = (grantResults[0] == PackageManager.PERMISSION_GRANTED);
                if (isPermissionGranted) {
                    onCreate(null);
                } else {
                    boolean cannotRequestAgain = shouldShowRequestPermissionRationale(permissions[0]);
                    if (cannotRequestAgain) {
                        finish();
                    } else {
                        Toast.makeText(this, "请去设置页面打开权限", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    }

    protected abstract String[] getPermissionList();
}
